﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

public partial class en_imageeditInterSpace_CutImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    private void Cutimage(string imgpath)
    {
        System.Drawing.Image initImage = System.Drawing.Image.FromFile(imgpath);
        //原始图片的宽、高
        int initWidth = initImage.Width;
        int initHeight = initImage.Height;

        //非正方型先裁剪为正方型
        if (initWidth != initHeight)
        {
            //截图对象
            System.Drawing.Image pickedImage = null;
            System.Drawing.Graphics pickedG = null;

            //宽大于高的横图
            if (initWidth > initHeight)
            {
                //对象实例化
                pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                //设置质量
                pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //定位
                Rectangle fromR = new Rectangle(initWidth / 2, initHeight / 2, 145, 145);

                Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
                //画图
                pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                //重置宽
                initWidth = initHeight;
            }
            //高大于宽的竖图
            else
            {
                //对象实例化
                pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                //设置质量
                pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //定位
                Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
                //画图
                pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                //重置高
                initHeight = initWidth;
            }

            //将截图对象赋给原图
            System.Drawing.Image newimage = (System.Drawing.Image)pickedImage.Clone();
            //释放截图资源
           

            newimage.Save(Guid.NewGuid().ToString() + "_Cut.jpg");
            pickedG.Dispose();
            pickedImage.Dispose();
        }
    }
}